package com.hx.config;

import cn.hutool.core.util.StrUtil;
import com.hx.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.security.Principal;

/**
 * 自定义 {@link ChannelInterceptor}
 *
 * @author zhangziyao
 */
@Slf4j
@Component
public class AuthChannelInterceptor implements ChannelInterceptor {

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
//        MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
//        if (accessor != null && accessor.isMutable()) {
//            accessor.setImmutable();
//        }
//        return message;

        /*StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            // 1) Perform authentication here using standard authentication providers (managers).
            //2) Install the user in case of successful authentication or throw an error
            accessor.setUser(new UserPrincipal("TEST USER 2"));
        }
        return message;*/

        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            String authorization = accessor.getNativeHeader("Authorization").get(0);
            if(StrUtil.startWith(authorization,"Bearer")) {
                log.info("【webSocket】 --- 连接success，authorization:{}",authorization);
                //todo,通过token获取用户信息，下方用loginUser来代替
                //如果存在用户信息，将用户名赋值，后期发送时，可以指定用户名即可发送到对应用户
                SysUser user = new SysUser();
                user.setUsername(StrUtil.replaceIgnoreCase(authorization,"Bearer ",""));
                user.setPassword("123456");
                accessor.setUser(user);
            }else{
                log.info("【webSocket】 --- 用户不合法");
                throw new RuntimeException("认证失败，Token不合法"+authorization);
            }
            /*Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if (raw instanceof Map) {
                String token = (String) ObjectUtil.defaultIfNull(((LinkedMultiValueMap)raw).getFirst("Authorization"),"");
                log.info("authorization：{}",token);
                if(StrUtil.isEmpty(token)){
                    log.error("【webSocket】 --- 连接fail，原因：authorization为空");
                    return message;
                }
                log.info("【webSocket】 --- 连接success");
                //通过token获取得到的用户对象
                User user = new User();
                user.setUsername("guest");
                user.setPassword("123456");
                accessor.setUser(user);
            }*/
        }else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
            Principal user = accessor.getUser();
            log.info("用户【{}】断开连接", user);
            log.info("————————————————————————————————————————————————————————————————");
        }
        return message;
    }
}
